package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker; //注入工具类

    @Override
    public String save(Video video) {
        //1. 设置属性
        video.setVid(idWorker.getNextId("video")); //通过工具类方法来获取唯一的数字id
        video.setCreated(System.currentTimeMillis());
        //2. 调用方法保存对象
        mongoTemplate.save(video);
        //3. 返回对象id （在mongo当中,如果保存成功,会自动赋值id）
        return video.getId().toHexString();
    }

    @Override
    public List<Video> findVideosByVids(List<Long> vids) {
        Query query = Query.query(Criteria.where("vid").in(vids));
        return mongoTemplate.find(query,Video.class);
    }

    @Override
    public List<Video> queryVideoList(int page, Integer pagesize) {
        Query query = new Query().limit(pagesize).skip((page-1)*pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Video.class);
    }

    @Override
    public void saveUserFocus(FocusUser focusUser) {
//        focusUser.setId(ObjectId.get());
        mongoTemplate.save(focusUser);
    }

    @Override
    public void deleteUserFocus(Long userId, Long followUserId) {
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId));
        mongoTemplate.remove(query,FocusUser.class);
    }


}
